import request from '@/utils/request'
import Cookies from 'js-cookie'
import axios from 'axios'

const sign = 'sign-upload'
const file_dir = 'project'

export function fetchPolicy(dir) {
  return request({
    url: '/oss/upload/policy',
    method: 'post',
    params: { dir }
  })
}

export async function uploadFileData(file, fileName) {
  return new Promise((resolve, reject) => {
    // 从cookies中取签名，判断签名有没有过期
    const signData = Cookies.get(sign)
    if (signData === undefined) {
      fetchPolicy(file_dir).then(response => {
        console.log('response!!!!-21', response)
        Cookies.set(sign, JSON.stringify(response.data))
        if (fileName) {
          const res = uploadFixFile(response.data, file, fileName)
          resolve(res)
        } else {
          const res = uploadFile(response.data, file)
          resolve(res)
        }
      }).catch(err => {
        console.log(err)
        reject(false)
      })
    } else {
      const response = JSON.parse(signData)
      console.log('response!!!!-37', response)
      const timestamp = Date.parse(new Date())
      if (response.expire - 3000 > timestamp) {
        // console.log('签名没过期')
        if (fileName) {
          const res = uploadFixFile(response, file, fileName)
          resolve(res)
        } else {
          const res = uploadFile(response, file)
          resolve(res)
        }
      } else {
        // 签名过期的话重新请求签名
        fetchPolicy(file_dir).then(response => {
          Cookies.set(sign, JSON.stringify(response.data))
          if (fileName) {
            const res = uploadFixFile(response.data, file, fileName)
            resolve(res)
          } else {
            const res = uploadFile(response.data, file)
            resolve(res)
          }
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      }
    }
  })
}

export async function uploadDirFile(fileDir, file, fileName) {
  return new Promise((resolve, reject) => {
    // 从cookies中取签名，判断签名有没有过期
    const signData = Cookies.get(sign)
    if (signData === undefined) {
      fetchPolicy(fileDir).then(response => {
        console.log('response!!!! dir-74', response)
        Cookies.set(sign, JSON.stringify(response.data))
        if (fileName) {
          const res = uploadFixFile(response.data, file, fileName)
          resolve(res)
        } else {
          const res = uploadFile(response.data, file)
          resolve(res)
        }
      }).catch(err => {
        console.log(err)
        reject(false)
      })
    } else {
      const response = JSON.parse(signData)
      console.log('response!!!! uploadDirFile-90', response)
      const timestamp = Date.parse(new Date())
      if (response.expire - 3000 > timestamp) {
        // console.log('签名没过期')
        if (fileName) {
          const res = uploadFixFile(response, file, fileName)
          resolve(res)
        } else {
          const res = uploadFile(response, file)
          resolve(res)
        }
      } else {
        // 签名过期的话重新请求签名
        fetchPolicy(fileDir).then(response => {
          Cookies.set(sign, JSON.stringify(response.data))
          if (fileName) {
            const res = uploadFixFile(response.data, file, fileName)
            resolve(res)
          } else {
            const res = uploadFile(response.data, file)
            resolve(res)
          }
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      }
    }
  })
}

async function uploadFile(data, file) {
  const ossData = new FormData()
  // 时间为了创建不同的层级目录，时间戳为了保证上传同一张图片不会被覆盖
  const { y, m, f } = getDateYmds()
  // ossData.append('name', file.file.name)
  // key就代表文件层级和阿里云上的文件名
  console.log('data==========', data)
  const suffix = file.name.substr(file.name.lastIndexOf('.'))
  ossData.append('name', f + suffix)
  ossData.append('key', data.dir + '/' + y + '/' + m + '/' + f + suffix)
  ossData.append('policy', data.policy)
  ossData.append('OSSAccessKeyId', data.accessid)
  // 阿里云正常返回204，然后返回信息是空的，想看到返回信息强制让它返回201，返回一个xml文件可以提取有用的信息
  ossData.append('success_action_status', 201)
  ossData.append('signature', data.signature)
  ossData.append('file', file, f + suffix)
  let retRes = ''
  await axios.post(data.host, ossData, {
    headers: {
      'Content-Type': 'multipart/form-data; boundary={boundary}'
    }
  }).then(res => {
    retRes = res
  }).catch(error => {
    console.log(error, '错误')
  })

  return retRes
}

async function uploadFixFile(data, file, fileName) {
  const ossData = new FormData()
  ossData.append('name', fileName)
  ossData.append('key', data.dir + '/' + fileName)
  ossData.append('policy', data.policy)
  ossData.append('OSSAccessKeyId', data.accessid)
  // 阿里云正常返回204，然后返回信息是空的，想看到返回信息强制让它返回201，返回一个xml文件可以提取有用的信息
  ossData.append('success_action_status', 201)
  ossData.append('signature', data.signature)
  ossData.append('file', file, fileName)
  let retRes = ''
  await axios.post(data.host, ossData, {
    headers: {
      'Content-Type': 'multipart/form-data; boundary={boundary}'
    }
  }).then(res => {
    retRes = res
  }).catch(error => {
    console.log(error, '错误')
  })

  return retRes
}

export function getDateYmds() {
  const date = new Date()
  const s = date.getTime()
  const y = date.getFullYear()
  const m = date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const d = date.getDate() < 9 ? '0' + date.getDate() : date.getDate()
  const r = Math.random().toString().slice(-3)

  return { y: y, m: m, d: d, s: s, f: s + r }
}
